﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;

namespace WpfAdvControls.File
{
    /// <summary>
    ///     Interaction logic for OpenFileBox.xaml
    /// </summary>
    public partial class OpenFileBox : UserControl, INotifyPropertyChanged
    {
        public static readonly DependencyProperty FileNameProperty =
            DependencyProperty.Register("FileName", typeof (string),
                typeof (OpenFileBox),
                new FrameworkPropertyMetadata(string.Empty,
                    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                    OnFileNameChanged));

        public OpenFileBox()
        {
            InitializeComponent();
            fileTextBox.Text = FileName;
        }

        /// <summary>
        ///     File name property by Deperndency property
        /// </summary>
        public string FileName
        {
            get { return (string) GetValue(FileNameProperty); }
            set { SetValue(FileNameProperty, value); }
        }

        private static void OnFileNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var box = d as OpenFileBox;
            if (box == null) return;
            box.fileTextBox.Text = e.NewValue as string;
            box.NotifyPropertyChanged("FileName");
        }

        private void OpenFileClick(object sender, RoutedEventArgs e)
        {
            var fileDialog = new OpenFileDialog();
            fileDialog.FileName = FileName;
            if (fileDialog.ShowDialog() == true)
            {
                FileName = fileDialog.FileName;
            }
        }

        private void fileTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (FileName != fileTextBox.Text)
            {
                FileName = fileTextBox.Text;
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }

        #endregion
    }
}